var app = getApp();
var face_token = '';
var sImg;
var sImageName;
// var avatarUrl;
// var nickName;

const APP_ID = 'wxb32df375196aa830'; //输入小程序appid  
const APP_SECRET = '83992cba8aa3b84abdd718ddb871b950'; //输入小程序app_secret  
var OPEN_ID = '' //储存获取到openid  
var SESSION_KEY = '' //储存获取到session_key 

const io = require('../../utils/weapp.socket.io.dev.js');
Page({
  data: {
    backgroundName1,
    backgroundName2,
    colorName1,
    colorName2,
    displayName1,
    displayName2,
    sImg: null,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    var that = this
    // getOpenIdTap(that);
    // wx.login({
    //   success: function () {
    //     wx.getUserInfo({
    //       success: function (res) {
    //         var simpleUser = res.userInfo;
    //         sImg = simpleUser.avatarUrl
    //         app.globalData.sName = simpleUser.nickName
    //         app.globalData.sImg = simpleUser.avatarUrl
    //         that.setData({
    //           nickName: simpleUser.nickName,
    //           sImg: simpleUser.avatarUrl,
    //         })
    //       }
    //     });
    //   }
    // });
  },
  button_registerFace(e) {
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) { // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: 'https://api-cn.faceplusplus.com/facepp/v3/detect',
          filePath: tempFilePaths[0],
          name: 'image_file',
          formData: {
            api_key: 'e7mQCRQH_yCEDxmMsVB-wKwCBMDrnEr-',
            api_secret: 'n5gRQq_T_nMghOgF9QW9hp8WLHmUna-h',
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: (res) => {
            var _data = JSON.parse(res.data);
            console.log(_data);
            if (res.statusCode == 200 && _data.faces[0].face_token) {
              face_token = _data.faces[0].face_token
              console.log(_data.faces[0].face_token)
              wx.showToast({
                title: '注册face成功',
                icon: 'success',
              })
            } else {
              wx.showToast({
                title: '注册face失败',
                image: '/images/error.png',
              })
            }
          },
          fail: (err) => {
            wx.showToast({
              title: '注册face失败',
              image: '/images/error.png',
            })
            console.error(err)
          }
        })
      }
    })
  },
  formSubmit_signIn(e) {
    var _sID = e.detail.value.sId
    var _sPassword = e.detail.value.sPassword
    if (_sID.length != 8) {
      wx.showModal({
        title: '提示',
        content: '请输入正确的8位数学号',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else if (_sPassword.length < 6) {
      wx.showModal({
        title: '提示',
        content: '密码长度不得少于6位',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      wx.request({
        url: "https://geek-team.xin/LAR/sLogin",
        method: 'POST',
        data: {
          sId: e.detail.value.sId,
          sPassword: e.detail.value.sPassword,
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: (res) => {
          console.log(res)
          if (res.data.result == true) {
            wx.showToast({
              title: '登录成功',
              icon: 'success',
            })
            app.globalData.sId = e.detail.value.sId;
            app.globalData.isStudent = true;

            app.globalData.socket = (this.socket = io(
              `https://geek-team.xin?sId=${app.globalData.sId}&isStudent=${app.globalData.isStudent}`,
            ))
            // console.log(app.globalData.socket)
            this.socket.on('connect', function () {
              console.log('You joined')
            })
            this.socket.on('connect_error', function () {
              console.log(`connect_error: `)
            })
            getCurrentSign(e);
            wx.navigateBack({
              delta: 1
            })
          } else if (res.data.message === "password is wrong") {
            console.log()
            wx.showModal({
              title: '登录失败',
              content: "密码错误，请重新输入",
            })
          } else {
            wx.showModal({
              title: '登录失败',
              content: "没有该用户，请先注册",
            })
          }
        },
        fail: (e) => console.log(`${e}`)
      })
    }
  },
  formSubmit_register(e) {
    var that = this
    var _data = e.detail.value;
    if (_data.sId.length != 8) {
      wx.showModal({
        title: '提示',
        content: '请输入正确的8位数学号',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else if (_data.sPassword.length < 6) {
      wx.showModal({
        title: '提示',
        content: '密码长度不得少于6位',
      })
    } else if (face_token === '') {
      wx.showModal({
        title: '提示',
        content: '请先检测人脸！',
      })
    }
    else {
      wx.request({
        url: 'https://geek-team.xin/LAR/sRegister',
        method: 'POST',
        data: {
          sId: _data.sId,
          openid: OPEN_ID,
          sPassword: _data.sPassword,
          sData: face_token,
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: (res) => {
          console.log(res)
          if (res.data == true) {
            wx.showToast({
              title: '注册成功',
              icon: 'success',
            })
            //跳转登录
            that.setData({
              background1: '#77c9d4',
              background2: '#ffffff',
              color1: '#f2ffff',
              color2: '#1a1a1a',
              display1: 'block',
              display2: 'none',
            })
          } else {
            wx.showToast({
              title: `注册失败`,
              image: '/images/error.png',
            })
          }
        },
        fail: (e) => console.log(`${e}`)
      })
    }

  },
  changeToSignin,
  changeToRegister,
})
/**
 * 获得当前正在签到的信息，并跳去签到界面
 */
function getCurrentSign(e) {
  wx.request({
    url: "https://geek-team.xin/offlineMessage/getCurrentSignBySid",
    method: 'POST',
    data: {
      sId: e.detail.value.sId,
    },
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success: (d) => {
      console.log(d)
      if (d.statusCode == 200 && d.data != null && d.data != "") {
        app.goToSign(d.data);
      }
    }
  });
}

/*
 * 获取openid的
 */
function getOpenIdTap(that) {
  wx.login({
    success: function (res) {
      console.log(res)
      wx.request({
        url: 'https://geek-team.xin/authorize',
        data: {
          js_code: res.code,
        },
        method: 'GET',
        success: function (res) {
          console.log(res.data)
          OPEN_ID = res.data.openid; //获取到的openid  
          SESSION_KEY = res.data.session_key; //获取到session_key  
          that.setData({
            openid: res.data.openid.substr(0, 10) + '********' + res.data.openid.substr(res.data.openid.length - 8, res.data.openid.length),
            session_key: res.data.session_key.substr(0, 8) + '********' + res.data.session_key.substr(res.data.session_key.length - 6, res.data.session_key.length)
          })
        }
      })
    }
  })
}
/*
 * 跳转注册
 */
function changeToRegister() {
  this.setData({
    background1: '#ffffff',
    background2: '#77c9d4',
    color1: '#1a1a1a',
    color2: '#f2ffff',
    display1: 'none',
    display2: 'block'
  })
}
/*
 * 跳转登录
 */
function changeToSignin() {
  this.setData({
    background1: '#77c9d4',
    background2: '#ffffff',
    color1: '#f2ffff',
    color2: '#1a1a1a',
    display1: 'block',
    display2: 'none',
  })
}
/*
 * 样式
 */
var backgroundName1 = {
  background1: '#77c9d4'
};
var backgroundName2 = {
  background2: '#ffffff'
};
var colorName1 = {
  color1: '#f2ffff'
};
var colorName2 = {
  color2: '#1a1a1a'
};
var displayName1 = {
  display1: 'block'
};
var displayName2 = {
  display2: 'none'
}